package com.ftwj.service;

    import com.ftwj.entity.SysMenu;
import com.ftwj.mapper.SysMenuListMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysMenuListService {
    @Autowired

    private SysMenuListMapper sysMenuListMapper;

    public List<SysMenu> getAllMenus(){

        return sysMenuListMapper.selectAllMenus();
    }

    public List<SysMenu> getMenusByParentId(String parentId){

        return sysMenuListMapper.selectByParentId(parentId);
    }

    public List<SysMenu> getMenuHierarchy() {
        List<SysMenu> allMenus = getAllMenus();
        return buildMenuHierarchy(allMenus);
    }
    private List<SysMenu> buildMenuHierarchy(List<SysMenu> menus) {
        // 获取顶级菜单
        List<SysMenu> topLevelMenus = menus.stream()
                .filter(menu -> "0".equals(menu.getParentId()))
                .collect(Collectors.toList());
        // 递归设置子菜单
        topLevelMenus.forEach(menu -> menu.setChildren(getSubMenus(menu, menus)));

        return topLevelMenus;
    }

    private List<SysMenu> getSubMenus(SysMenu parentMenu, List<SysMenu> allMenus) {
        return allMenus.stream()
                .filter(menu -> parentMenu.getId().equals(menu.getParentId()))
                .peek(menu -> menu.setChildren(getSubMenus(menu, allMenus)))
                .collect(Collectors.toList());
    }

    public List<SysMenu> getMenuByName(String menuName) {
        return sysMenuListMapper.selectMenuByName(menuName);
    }

}
